var crypto = require('../utils/crypto');
var express = require('express');
var db = require('../utils/db');
var http = require("../utils/http");
var ProtoBuf = require('protobufjs');

var app = express();
var hallAddr = "";

function send(res,ret){
	var str = JSON.stringify(ret);
	res.send(str)
}

var config = null;

var webRoot = './';
var protobufDir = webRoot;

exports.start = function(cfg){
	config = cfg;
	hallAddr = config.HALL_IP  + ":" + config.HALL_CLIENT_PORT;
	app.listen(config.CLIENT_PORT);
	console.log("account server is listening on " + config.CLIENT_PORT);

	console.log("exportstart="+ProtoBuf);

	ProtoBuf.load(protobufDir+'TestProtobuf.proto', function(err, root) {
		console.log("exports11tart="+err);
		if (err)
			throw err;
	 
		// Obtain a message type
		var AwesomeMessage = root.lookupType("TestProto");
	 
		// Exemplary payload
		var payload = { id:1000,name: "ShawnZhang" };
	 
		// Verify the payload if necessary (i.e. when possibly incomplete or invalid)
		var errMsg = AwesomeMessage.verify(payload);
		console.log("procfesss1111="+errMsg);
		if (errMsg)
			throw Error(errMsg);
	 
		// Create a new message
		var message = AwesomeMessage.create(payload); // or use .fromObject if conversion is necessary
		console.log("procfess2211="+message);
	 
		// Encode a message to an Uint8Array (browser) or Buffer (node)
		var buffer = AwesomeMessage.encode(message).finish();
		console.log("procfess3311="+buffer);
		// ... do something with buffer
	 
		// Decode an Uint8Array (browser) or Buffer (node) to a message
		var message1 = AwesomeMessage.decode(buffer);
		console.log("procfess4411="+message1.id+" "+message1.name);
		// ... do something with message
	 
		// If the application uses length-delimited buffers, there is also encodeDelimited and decodeDelimited.
	 
		// Maybe convert the message back to a plain object
		var object = AwesomeMessage.toObject(message1, {
			longs: String,
			enums: String,
			bytes: String,
			int:String,
			// see ConversionOptions
		});
		console.log("procfess5511="+object);
	});
	console.log("exportstart1122222=");

	// var TestProtobuf = ProtoBuf.load(protobufDir+'TestProtobuf.proto').build('TestProtobuf'),
	// TestProto = TestProtobuf.TestProto;
	// var testProto = new TestProto({
	// 	id:10014,
	// 	name:'testProtoName测试987'
	// });
	// console.log("procfesss1111="+testProto);
	// var testProtoData = TestProto.decode(testProto.toBuffer());
	// console.log("procfesss2211="+(testProto.toBuffer()));
	// console.log("procfesss3311="+testProtoData);
}





//设置跨域访问
app.all('*', function(req, res, next) {
    // res.header("Access-Control-Allow-Origin", "*");
    // res.header("Access-Control-Allow-Headers", "X-Requested-With");
    // res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
    // res.header("X-Powered-By",' 3.2.1')
	// res.header("Content-Type", "application/x-protobuf");
	res.setHeader("Access-Control-Allow-Origin", "*");
    res.setHeader("Access-Control-Allow-Credentials", "true");
    res.setHeader("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT");
	res.setHeader("Access-Control-Allow-Headers", "Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers");
	res.header("Content-Type", "application/octet-stream");
    next();
});

app.get('/register',function(req,res){
	var account = req.query.account;
	var password = req.query.password;

	var fnFailed = function(){
		send(res,{errcode:1,errmsg:"account has been used."});
	};

	var fnSucceed = function(){
		send(res,{errcode:0,errmsg:"ok"});	
	};

	db.is_user_exist(account,function(exist){
		if(exist){
			db.create_account(account,password,function(ret){
				if (ret) {
					fnSucceed();
				}
				else{
					fnFailed();
				}
			});
		}
		else{
			fnFailed();
			console.log("account has been used.");			
		}
	});
});

app.get('/get_version',function(req,res){
	var ret = {
		version:config.VERSION,
	}
	send(res,ret);
});

app.post('/get_serverinfo', function (req, res) {
	// req.rawBody = '';//添加接收变量
	// var json={};
	// req.setEncoding('utf8');
	req.on('data', function(chunk) { 
		console.log("procfesss11="+chunk);
		console.log("eneneneenenne=");
		if(!(chunk instanceof ArrayBuffer))return;
		ProtoBuf.load(protobufDir+'TestProtobuf.proto', function(err, root) {
			console.log("exports11tart="+err);
			if (err)
				throw err;
		 
			// Obtain a message type
			var AwesomeMessage = root.lookupType("TestProto");

			// Exemplary payload
			var payload = { id:1000,name: "ShawnZhang" };
		
			// Verify the payload if necessary (i.e. when possibly incomplete or invalid)
			var errMsg = AwesomeMessage.verify(payload);
			console.log("procfesss1111="+errMsg);
			if (errMsg)
				throw Error(errMsg);
		
			// Create a new message
			var message = AwesomeMessage.create(payload); // or use .fromObject if conversion is necessary
			console.log("procfess2211="+message);
		
			// Encode a message to an Uint8Array (browser) or Buffer (node)
			var buffer = AwesomeMessage.encode(message).finish();
			console.log("procfess3311="+buffer);
			// ... do something with buffer
		
			// Decode an Uint8Array (browser) or Buffer (node) to a message
			var message1 = AwesomeMessage.decode(buffer);
			console.log("procfess4411="+message1.id+" "+message1.name);
			// ... do something with message

			console.log("aaaaaaaaaa77aaaa="+(typeof buffer));
			console.log("aaaaaaaaa99aaaaa="+(typeof chunk));

			console.log("aaaaaaaaaa33aaaa="+(buffer===chunk));
			console.log("aaaaaaaaa44aaaaa="+(buffer==chunk));

			console.log("aaaaaaaaaaaaaa="+(buffer instanceof Uint8Array));
			console.log("aaaaaaaaaaaaaabbbbbbbb="+Array.isArray(buffer));
	
			console.log("aaaaaaaaaaaaa11a="+(chunk instanceof Uint8Array));
			console.log("aaaaaaaaaaaaaabbbbb22bbb="+Array.isArray(chunk));

			message1 = AwesomeMessage.decode(chunk);
			console.log("procfess7711="+message1.id+" "+message1.name);
		});
	//   req.rawBody += chunk;
	});
	req.on('end', function() {
	//   json=xml2json.toJson(req.rawBody);
	//   res.send(JSON.stringify(json));
		var ret = {
			version:config.VERSION,
			hall:hallAddr,
			appweb:config.APP_WEB,
		};
		console.log("aaaaaaaaaaaaaabbbbb22bb11b="+ret);
		// ... do something with message
		send(res,ret);
	}); 
  });

// app.post('/get_serverinfo',function(req,res){
// 	var ret = {
// 		version:config.VERSION,
// 		hall:hallAddr,
// 		appweb:config.APP_WEB,
// 	}
// 	console.log("apppppppppreq="+req);	
// 	console.log("apppppppppres="+res);
// 	ProtoBuf.load(protobufDir+'TestProtobuf.proto', function(err, root) {
// 		console.log("exports11tart="+err);
// 		if (err)
// 			throw err;
	 
// 		// Obtain a message type
// 		var AwesomeMessage = root.lookupType("TestProto");

	 
// 		// Decode an Uint8Array (browser) or Buffer (node) to a message
// 		console.log("procfess771111="+req.body);
// 		console.log("procfess77111122="+req.params);
// 		console.log("procfess77111133="+req.query);
// 		console.log("procfess77111177="+JSON.stringify(req.params));
// 		var message1 = AwesomeMessage.decode(req.body);
// 		console.log("procfess7711="+message1.id+" "+message1.name);
// 		// ... do something with message

// 	});
// 	// var sparrow_pb = require('sparrow_pb');
// 	// console.log("onloadddddd="+sparrow_pb);

// 	// var message = new sparrow_pb.CMD_S2C_StatusFree();
// 	// console.log("CMD_S2C_StatusFree==="+message);
// 	// message.setWbankeruser(12);
// 	// console.log("getmessgbox="+message.getWbankeruser());
// 	// var b = message.serializeBinary();
// 	// console.log("bbbbbb="+b);
// 	send(res,ret);
// });

app.get('/guest',function(req,res){
	var account = "guest_" + req.query.account;
	console.log("getsut="+account);
	var sign = crypto.md5(account + req.ip + config.ACCOUNT_PRI_KEY);
	var ret = {
		errcode:0,
		errmsg:"ok",
		account:account,
		halladdr:hallAddr,
		sign:sign
	}
	send(res,ret);
});

app.get('/auth',function(req,res){
	var account = req.query.account;
	var password = req.query.password;

	db.get_account_info(account,password,function(info){
		if(info == null){
			send(res,{errcode:1,errmsg:"invalid account"});
			return;
		}

        var account = "vivi_" + req.query.account;
        var sign = get_md5(account + req.ip + config.ACCOUNT_PRI_KEY);
        var ret = {
            errcode:0,
            errmsg:"ok",
            account:account,
            sign:sign
        }
        send(res,ret);
	});
});

var appInfo = {
	Android:{
		appid:"wxe39f08522d35c80c",
		secret:"fa88e3a3ca5a11b06499902cea4b9c01",
	},
	iOS:{
		appid:"wxcb508816c5c4e2a4",
		secret:"7de38489ede63089269e3410d5905038",		
	}
};

function get_access_token(code,os,callback){
	var info = appInfo[os];
	if(info == null){
		callback(false,null);
	}
	var data = {
		appid:info.appid,
		secret:info.secret,
		code:code,
		grant_type:"authorization_code"
	};

	http.get2("https://api.weixin.qq.com/sns/oauth2/access_token",data,callback,true);
}

function get_state_info(access_token,openid,callback){
	var data = {
		access_token:access_token,
		openid:openid
	};

	http.get2("https://api.weixin.qq.com/sns/userinfo",data,callback,true);
}

function create_user(account,name,sex,headimgurl,callback){
	var coins = 1000;
	var gems = 21;
	db.is_user_exist(account,function(ret){
		if(!ret){
			db.create_user(account,name,coins,gems,sex,headimgurl,function(ret){
				callback();
			});
		}
		else{
			db.update_user_info(account,name,headimgurl,sex,function(ret){
				callback();
			});
		}
	});
};
app.get('/wechat_auth',function(req,res){
	var code = req.query.code;
	var os = req.query.os;
	if(code == null || code == "" || os == null || os == ""){
		return;
	}
	console.log(os);
	get_access_token(code,os,function(suc,data){
		if(suc){
			var access_token = data.access_token;
			var openid = data.openid;
			get_state_info(access_token,openid,function(suc2,data2){
				if(suc2){
					var openid = data2.openid;
					var nickname = data2.nickname;
					var sex = data2.sex;
					var headimgurl = data2.headimgurl;
					var account = "wx_" + openid;
					create_user(account,nickname,sex,headimgurl,function(){
						var sign = crypto.md5(account + req.ip + config.ACCOUNT_PRI_KEY);
					    var ret = {
					        errcode:0,
					        errmsg:"ok",
					        account:account,
					        halladdr:hallAddr,
					        sign:sign
					    };
					    send(res,ret);
					});						
				}
			});
		}
		else{
			send(res,{errcode:-1,errmsg:"unkown err."});
		}
	});
});

app.get('/base_info',function(req,res){
	var userid = req.query.userid;
	db.get_user_base_info(userid,function(data){
		var ret = {
	        errcode:0,
	        errmsg:"ok",
			name:data.name,
			sex:data.sex,
	        headimgurl:data.headimg
	    };
	    send(res,ret);
	});
});